//
//  XYHomeViewController.m
//  新项目
//
//  Created by xmy on 2017/2/22.
//  Copyright © 2017年 xmy. All rights reserved.
//

#import "XYHomeViewController.h"
#import "GYZChooseCityController.h"
#import "HMDiscoverSearchView.h"
#import "WYChannelView.h"
#import "WYChannelModel.h"
#import "XYChannelListViewController.h"
#import "XYHomeTableViewController.h"


@interface XYHomeViewController ()<GYZChooseCityDelegate,UICollectionViewDataSource, UICollectionViewDelegate, WYChannelViewDelegate>
@property(nonatomic,copy)NSString *cityName;
@property (nonatomic , strong)UIBarButtonItem *leftButton;
/**
 *  频道的视图
 */
@property (nonatomic, strong) WYChannelView *channelView;
/**
 *  记录频道的数据
 */
@property (nonatomic, strong) NSArray *channels;

/**
 *  显示新闻 的collectionView
 */
@property (nonatomic, weak) UICollectionView *collectionView;
/**
 *  用于缓存控制器的字典
 */
@property (nonatomic, strong) NSMutableDictionary *vcCache;
/**
 *  广告视图
 */
@property (nonatomic, weak) UIView *adView;

@end
static NSString *newsCellId = @"newsCellId";

@implementation XYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor randomColor];
    [self setupUI];
    //左侧按钮
//    NSString *titleString =(self.cityName == nil) ? @"选择城市" : self.cityName;
//    NSLog(@"---%@ ---%@",titleString,self.cityName);
    
    self.leftButton = [[UIBarButtonItem alloc]initWithTitle:(self.cityName == nil) ? @"全部地区" : self.cityName style:UIBarButtonItemStylePlain target:self action:@selector(buttonClick)];
    self.leftButton.tintColor = [UIColor blackColor];
//    [self.leftButton setImage:[UIImage imageNamed:@"index_bendituijian_normal"]];
//    [self.leftButton setWidth:50];
    self.navigationItem.leftBarButtonItems = @[self.leftButton];
    
    
    //搜索按钮
    HMDiscoverSearchView *sc = [HMDiscoverSearchView discoverSearchView];
    
    sc.frame = CGRectMake(0, 0, self.view.bounds.size.width-90, 35);
    sc.alpha = 0.01;
    [sc addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = sc;
    
    //频道
    [WYChannelModel channels];
    
    // 添加边缘手势
    UIScreenEdgePanGestureRecognizer *ges = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(showAd:)];
    // 指定左边缘滑动
    ges.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:ges];
    // 如果ges的手势与collectionView手势都识别的话,指定以下代码,代表是识别传入的手势
    [self.collectionView.panGestureRecognizer requireGestureRecognizerToFail:ges];
    
    //建立第一个控制器
//    XYHomeTableViewController *homeVC = [[XYHomeTableViewController alloc]init];
//    [self.collectionView addSubview:homeVC.view];
//    [self addChildViewController:homeVC];
//    [homeVC didMoveToParentViewController:self];
    
}
#pragma mark 搜索框的点击事件
#pragma mark - GYZCityPickerDelegate
- (void) cityPickerController:(GYZChooseCityController *)chooseCityController didSelectCity:(GYZCity *)city
{
//    [chooseCityBtn setTitle:city.cityName forState:UIControlStateNormal];
    self.cityName = city.cityName;
    [chooseCityController dismissViewControllerAnimated:YES completion:^{
        [self.leftButton setTitle:self.cityName];
    }];
}

- (void) cityPickerControllerDidCancel:(GYZChooseCityController *)chooseCityController
{
    [chooseCityController dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)searchButtonClick{
    
//    NSLog(@"你点击了搜索框功能");
//        [self.navigationController presentViewController:[NSClassFromString(@"XYSearchViewController") new] animated:YES completion:nil];
    
    [self.navigationController pushViewController:[NSClassFromString(@"XYSearchViewController") new]  animated:YES];
}
#pragma mark 左侧按钮点击
- (void)buttonClick{
    GYZChooseCityController *cityPickerVC = [[GYZChooseCityController alloc] init];
    [cityPickerVC setDelegate:self];
    
    //    cityPickerVC.locationCityID = @"1400010000";
    //    cityPickerVC.commonCitys = [[NSMutableArray alloc] initWithArray: @[@"1400010000", @"100010000"]];        // 最近访问城市，如果不设置，将自动管理
    //    cityPickerVC.hotCitys = @[@"100010000", @"200010000", @"300210000", @"600010000", @"300110000"];
    
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:cityPickerVC] animated:YES completion:^{
        
    }];
}
#pragma mark 频道逻辑
- (void)showAd:(UIScreenEdgePanGestureRecognizer *)ges {
    // 让view跟着手指去移动
    // frame的x应该为多少??应该获取到手指的x值
    // 取到手势在当前控制器视图中识别的位置
    CGPoint p = [ges locationInView:self.view];
    NSLog(@"%@", NSStringFromCGPoint(p));
    CGRect frame = self.adView.frame;
    // 更改adView的x值. 手指的位置 - 屏幕宽度
    frame.origin.x = p.x - [UIScreen mainScreen].bounds.size.width;
    // 重新设置上去
    self.adView.frame = frame;
    
    if (ges.state == UIGestureRecognizerStateEnded || ges.state == UIGestureRecognizerStateCancelled) {
        // 判断当前广告视图在屏幕上显示是否超过一半
        if (CGRectContainsPoint(self.view.frame, self.adView.center)) {
            // 如果超过,那么完全展示出来
            frame.origin.x = 0;
        }else{
            // 如果没有,隐藏
            frame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        }
        [UIView animateWithDuration:0.25 animations:^{
            self.adView.frame = frame;
        }];
    }
    
}

/**
 *  添加子控件
 */
- (void)setupUI {
    // 关闭控制器的自动调用ScrollView的属性
    self.automaticallyAdjustsScrollViewInsets = false;
    
    WYChannelView *channelView = [WYChannelView channelView];
    // 让控制器成为频道视图代理
    channelView.delegate = self;
    // 将频道数据存储到当前控制器
    self.channels = [WYChannelModel channels];
    // 读取频道数据,并且设置到频道视图上
    channelView.channels = self.channels;
    [self.view addSubview:channelView];
    // 记录当前添加的频道视图
    self.channelView = channelView;
    
    [channelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(35);
        make.top.equalTo(self.mas_topLayoutGuideBottom);
    }];
    
    [self setupCollectionView];
    [self setupAdView];
    
}

/**
 *  添加广告的view
 */
- (void)setupAdView {
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    // 设置背景颜色
//    view.backgroundColor = [UIColor randomColor];
    CGRect frame = view.frame;
    // 将x值改成负的屏幕宽度,原因是因为默认就在屏幕的左边
    frame.origin.x = -view.frame.size.width;
    // 设置给view
    view.frame = frame;
    // 因为该view是盖在所有的view身上,所以应该添加到window上
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    self.adView = view;
    
    // 添加轻扫手势
    UISwipeGestureRecognizer *ges = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(closeAd)];
    ges.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.adView addGestureRecognizer:ges];
}

- (void)closeAd {
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.adView.frame;
        frame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        self.adView.frame = frame;
    }];
}

/**
 *  设置collectionView
 */
- (void)setupCollectionView {
    
    // 初始化一个layout 供collectionView使用
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置滚动方向为水平
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 将行间距与列间距都设置为0
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    // 通过 layout 初始化一个collectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    // 设置背景颜色
    collectionView.backgroundColor = [UIColor whiteColor];
    // 注册成cell
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:newsCellId];
    // 让当前控制器成为collectionView的数据源
    collectionView.dataSource = self;
    collectionView.delegate = self;
    // 开启分页的属性
    collectionView.pagingEnabled = true;
    // 添加控件
    [self.view addSubview:collectionView];
    // 记录一下当前的collectionView
    self.collectionView = collectionView;
    // 添加约束
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.channelView.mas_bottom);
        make.leading.trailing.bottom.equalTo(self.view);
    }];
    
}
/**
 *  控制器中的视图布局完成之后会调用这个方法
 */
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 取到layout
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    // 设置大小
    layout.itemSize = self.collectionView.frame.size;
    NSLog(@"%@",NSStringFromCGRect(self.collectionView.frame));
}

#pragma mark - WYChannelViewDelegate

- (void)channelView:(WYChannelView *)channelView clickWithIndex:(NSInteger)index {
//    NSLog(@"点击了%zd",index);
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    // 如何让collecctionView滚动到指定的cell
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:false];
}

#pragma mark - UICollectionViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat ratio = scrollView.contentOffset.x / scrollView.frame.size.width;
//    NSLog(@"%f",ratio);
    
    //取出当前页面的索引
    NSInteger index = ratio / 1;
    
    //根据滚动距离求出缩放比例
    CGFloat scale = ratio - index;
    
    // 控制器不用关心每个label到底应该怎么缩放,只需要告诉 WYChannelView 哪个位置的label缩放以及缩放比例是多少就可以了.
    // 前提:从右往左滑
    // index: 代表移动之前的页面
    // index+1: 代表要显示的界面
    if (index + 1 < self.channels.count) {
        // 设置下一个页面的缩放比例
        [self.channelView setScale:scale forIndex:index + 1];
        // 设置滑动之前显示页面的缩放比例
        [self.channelView setScale:1 - scale forIndex:index];
//        NSLog(@"之前显示的页面索引 %zd, 即将要显示的页面索引 %zd, 当前比例: %f", index, index + 1, scale);
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.channels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 从缓存池中取出cell
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:newsCellId forIndexPath:indexPath];
    // 设置随机颜色供测试使用
    // cell.backgroundColor = [UIColor randomColor];
    // 移除cell中的contentView的子控件
    //    for (UIView *v in cell.contentView.subviews) {
    //        [v removeFromSuperview];
    //    }
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 取出模型
//    WYChannelModel *model = [self.channels objectAtIndex:indexPath.item];
    
    // 将新闻列表控制器的 view 添加到cell的contentView里面
//    UIViewController *vc = [self viewControlerWithModel:model];
//    // 添加当前控制器的View
//    [cell.contentView addSubview:vc.view];
//    
//    // 约束控制器的View与cell的大小一样大
//    [vc.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(cell.contentView);
//    }];
//    //    // 添加到当前控制器的子控制中
//    //    [self addChildViewController:vc];
    if(indexPath.row == 0){
        XYHomeTableViewController *homeVC = [[XYHomeTableViewController alloc]init];
        [self addChildViewController:homeVC];
        [cell.contentView addSubview: homeVC.view];
        [homeVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(cell.contentView);
        }];
    }
    
    return cell;
}

/**
 *  从缓存中通过频道模型去取数据,如果缓存中没有的话,创建一个保存到缓存中,并返回
 *
 *  @param model <#model description#>
 *
 *  @return <#return value description#>
 */
- (UIViewController *)viewControlerWithModel:(WYChannelModel *)model {
    
    // 从缓存中去取控制器
    UIViewController *vc = [self.vcCache objectForKey:model.tid];

    return vc;
}
#pragma mark - 懒加载

- (NSMutableDictionary *)vcCache {
    if (_vcCache == nil) {
        _vcCache = [NSMutableDictionary dictionary];
    }
    return _vcCache;
}
@end
